import 'package:bpb/db/db_helper.dart';
import 'package:bpb/framework/base/base_controller.dart';
import 'package:bpb/framework/utils/date_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:table_calendar/table_calendar.dart';

import '../../common/CommonData.dart';

class HomeController extends BaseController {
  var calendarFormat = CalendarFormat.month.obs;
  var focusedDay = DateTime.now().obs;
  var selectedDay = DateTime.now().obs;
  var bloodInfos = [].obs; //当前选中的日期的数据

  var currentLevel = "".obs;
  var currentLevelLabel = "".obs;
  var bloodLevels =
      [
        {"level": CommonData.BLOOD_PRESSURE_HYPOTENSION, "color": const Color(0xffCCD9FA), "checked": false},
        {"level": CommonData.BLOOD_PRESSURE_NORMAL, "color": const Color(0xffD7EACA), "checked": true},
        {"level": CommonData.BLOOD_PRESSURE_ELEVATED, "color": const Color(0xffF7E3C4), "checked": false},
        {"level": CommonData.BLOOD_PRESSURE_HYPERTENSIVE1, "color": const Color(0xffF7CDC4), "checked": false},
        {"level": CommonData.BLOOD_PRESSURE_HYPERTENSIVE2, "color": const Color(0xffFFA49E), "checked": false},
        {"level": CommonData.BLOOD_PRESSURE_HYPERTENSIVE, "color": const Color(0xffE57373), "checked": false},
      ].obs;

  var dataMaps = {}.obs;

  DateTime? pinDate; //当前选中的日期

  @override
  void onInit() {
    super.onInit();
    initLoad();
  }

  ///获取当前3月的时间列表，根据这个时间列表查询记录数据条数
  List<String> getMonthDatesWithAdjacent(DateTime baseDate) {
    // 获取上月、当前月、下月的第一天
    DateTime prevMonth = DateTime(baseDate.year, baseDate.month - 1, 1);
    DateTime currentMonth = DateTime(baseDate.year, baseDate.month, 1);
    DateTime nextMonth = DateTime(baseDate.year, baseDate.month + 1, 1);

    // 合并三个列表并格式化
    return [..._getMonthDates(prevMonth), ..._getMonthDates(currentMonth), ..._getMonthDates(nextMonth)].map((date) => _formatDate(date)).toList();
  }

  // 获取指定月份的所有日期
  List<DateTime> _getMonthDates(DateTime monthDate) {
    DateTime firstDay = DateTime(monthDate.year, monthDate.month, 1);
    DateTime nextMonthFirstDay = DateTime(monthDate.year, monthDate.month + 1, 1);
    int daysInMonth = nextMonthFirstDay.difference(firstDay).inDays;

    return List.generate(daysInMonth, (i) => firstDay.add(Duration(days: i)));
  }

  // 格式化为 yyyy-MM-dd
  String _formatDate(DateTime date) {
    return "${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}";
  }

  //实时更新当前的血压水平
  checkCurrentBloodPressureLevel(int sys, int dia) {
    try {
      List<String> level = CommonData.getBloodPressureLevel(sys, dia);
      currentLevel.value = level[0];
      currentLevelLabel.value = level[1];
      for (var ele in bloodLevels.value) {
        if (ele["level"] == currentLevel.value) {
          ele["checked"] = true;
        } else {
          ele["checked"] = false;
        }
      }
      bloodLevels.value = List.of(bloodLevels.value);
    } catch (e) {}
  }

  Color getLevelBorderColor(String level) {
    Color defaultColor = const Color(0xffD7EACA);
    Color resultColor = defaultColor;
    for (var element in bloodLevels.value) {
      Color color = element["color"] as Color;
      String xlevel = element["level"] as String;
      if (xlevel == level) {
        resultColor = color;
        break;
      }
    }
    return resultColor;
  }

  getDataByDate(String day) async {
    var datas = (await DBHelper.getRecordsByDate(day));
    return datas;
  }

  ///首次进来加载数据
  initLoad({DateTime? defaultDate = null}) {
    onPageChanged(DateTime.now());
    Future.delayed(Duration(seconds: 1), () {
      onDateSelected(defaultDate ?? DateTime.now());
    });
  }

  ///页面变化的时候查询最近3个月的数据
  Future<void> onPageChanged(DateTime day) async {
    List<String> dates = getMonthDatesWithAdjacent(day);
    for (var d in dates) {
      List<dynamic> datas = await getDataByDate(d);
      dataMaps[d] = datas;
    }
    dataMaps.value = Map.of(dataMaps.value);
  }

  ///选中日期查询对应的数据条数
  void onDateSelected(DateTime selectedDay) {
    pinDate = selectedDay;
    debugPrint("select date ${selectedDay}");
    bloodInfos.value = dataMaps[DateUtil.DF_YMD.format(selectedDay)] ?? [];
    for (var e in bloodInfos.value) {
      debugPrint("--->${e}");
    }
  }

  ///删除后刷新
  void onDeleteRefresh() {
    initLoad(defaultDate: pinDate);
  }
}
